package practice07;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * @author Administrator
 * @version V1.0
 * @ProjectName:IntelliJ IDEA
 * @PackageName: practice07
 * @ClassName: Client
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2020/1/3 10:45
 * @Copyright 大牛版板所有
 */
public class Client {
    //声明客户端套接字Socket
    static Socket client = null;

    public static void main(String[] args) {
        BufferedReader in = null;
        try {
            client = new Socket("localhost",9000);

            //发送消息的线程
            new ClientSendMsg().start();

            in = new BufferedReader(new InputStreamReader(client.getInputStream(),
                    Charset.forName("UTF-8")));
            //读取服务器给所有客户端分发的信息
            String line = null;
            while((line = in.readLine()) != null){
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //成员内部类
    private static class ClientSendMsg extends Thread{

        @Override
        public void run() {
            PrintWriter out = null;
            Scanner input = new Scanner(System.in);
            String message = null;
            while(true){
                try {
                    out = new PrintWriter(client.getOutputStream(),true);
                    message = input.nextLine(); //接收键盘输入
                    if("quit".equalsIgnoreCase(message)){
                        break;
                    }
                    out.println(message);//将消息发送给服务器
                    out.flush(); //手工清空缓冲区
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
